package Olivia.olivia3d.model.ms3d
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.net.URLStream;
	import flash.utils.Endian;
	
	public class PriMs3dLoader extends EventDispatcher
	{
		private var _urlstream:URLStream;
		
		private var _loading:Boolean;
		private var _file:String;
		private var _callBack:Function;
		private var _param:*;
		
		public function PriMs3dLoader()
		{
			_urlstream = new URLStream();
			_urlstream.addEventListener(Event.COMPLETE, completeLoader);
			_urlstream.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		}
		
		private function ioErrorHandler(e:IOErrorEvent):void
		{
			trace("ioErrorHandler: " + e);
		}
		
		protected function completeLoader(event:Event):void
		{			
			var dataStream:URLStream = event.target as URLStream;
			dataStream.endian = Endian.LITTLE_ENDIAN;
			var returnRes:Ms3dStruct = new Ms3dStruct(dataStream);
			Ms3dManager.models[_file] = returnRes;
			
			if(_callBack != null)
			{
				if(_param == null)
				{
					_callBack.call(null, returnRes);
				}
				else
				{
					_callBack.call(null, returnRes, _param);
				}
			}
			
			_loading = false;
			
			dispatchEvent(new Event(Event.COMPLETE));
			
			trace("resource load complete: " + _file);
		}
		
		public function load(file:String, callback:Function=null, param:*=null):void
		{
			_file = file;
			_callBack = callback;
			_param = param;
			
			_urlstream.load(new URLRequest(_file));
			_loading = true;
		}
		
		public function get loading():Boolean
		{
			return _loading;
		}
		
		public function get file():String
		{
			return _file;
		}
	}
}